/**
 * Created by Administrator on 2015/12/17.
 */
"use strict";
var F = require('../../../common/function');
var ware_F = require('./ware_common');
var _o2oServiceApi = require('../../../common/o2oServiceApi');
var o2oServiceApi = new _o2oServiceApi;
var _ = require('underscore');

exports.ware_update = function *(ware, key_validate_array) {
  let obj_ware_for_update = {};
  let keys_for_update_array = [];
  for (let p of key_validate_array) {
    if (ware[p] != undefined) {
      obj_ware_for_update[p] = ware[p];
      keys_for_update_array.push(p);
    }
  }
  
  let error_msg = ware_F.validateFields(obj_ware_for_update, keys_for_update_array);
  if (error_msg != '') {
    return F.returnMsg(400, error_msg, 1);
  }
  obj_ware_for_update.act = 1;
  obj_ware_for_update.status = 0;
  obj_ware_for_update.id = parseInt(ware.id);

  if (ware.categories && !_.isEmpty(ware.categories)) {
    obj_ware_for_update.cateCodes = yield F.array_2_codeArray(ware.categories, 'code');
    delete obj_ware_for_update.categories;
  }
  if (ware.shops && !_.isEmpty(ware.shops)) {
    obj_ware_for_update.shopids = yield F.array_2_codeArray(ware.shops, 'sid');
    delete obj_ware_for_update.shops;
  }
  if (ware.services && !_.isEmpty(ware.services)) {
    obj_ware_for_update.serverCodes = yield F.array_2_codeArray(ware.services, 'code');
    delete obj_ware_for_update.services;
  }

  yield ware_F.generate_img_signature(obj_ware_for_update);
  let upYunSign = obj_ware_for_update.upYunSign;


  let wareResult = yield o2oServiceApi.post('ware', 'updateVersion', 1, obj_ware_for_update);
  if (parseInt(wareResult['result']['error']) == 1 || wareResult.status == 400) {
    return F.returnMsg(300, wareResult['message']['msg'], 1);
  } else {
    if (!_.isEmpty(upYunSign)) {
      wareResult['result'].upYunSign = upYunSign;
    }
    wareResult['result'] = ware_F.deleteUnuselessFields(wareResult['result']);
    return F.returnMsg(200, '保存成功', 1, wareResult['result']);
  }
};